import datetime
import logging

import chinese_calendar
import time
from pymysql import *
import guowuyuanholiday

config = {
	'user': 'root',
	'password': 'xxx',
	'host': 'xxx',
	'port': 3306,
	'database': 'xxx',
	'charset': 'utf8'
}


def get_holidays(year=None, include_weekends=True):
	"""
	获取某一年的所有节假日，默认当年
	:param year: which year
	:param include_weekends: False for excluding Saturdays and Sundays
	:return: list
	"""
	print("节假日取数开始")
	print('chinese_calendar开始')
	if not year:
		year = datetime.datetime.now().year
	else:
		year = year
	start = datetime.date(year, 1, 1)
	end = datetime.date(year, 12, 31)
	holidays = chinese_calendar.get_holidays(start, end, include_weekends)

	print('chinese_calendar结束')
	print("节假日取数结束")
	return holidays


def add_holidays_info(holidaysList):
	"""遍历数组的几种方式
	list = ['html', 'js', 'css', 'python']
	# 方法1
	print '遍历列表方法1：'
	for i in list:
		print ("序号：%s   值：%s" % (list.index(i) + 1, i))
	print '\n遍历列表方法2：'
	# 方法2
	for i in range(len(list)):
		print ("序号：%s   值：%s" % (i + 1, list[i]))
	# 方法3
	print '\n遍历列表方法3：'
	for i, val in enumerate(list):
		print ("序号：%s   值：%s" % (i + 1, val))
	# 方法3
	print '\n遍历列表方法3 （设置遍历开始初始位置，只改变了起始序号）：'
	for i, val in enumerate(list, 2):
		print ("序号：%s   值：%s" % (i + 1, val))
	"""
	usersvalues = []
	for ii in range(len(holidaysList)):
		usersvalues.append((holidaysList[ii].date, holidaysList[ii].type, holidayDos[ii].desc))  # 注意要用两个括号扩起来
	conn = connect(**config)
	cs = conn.cursor()  # 获取光标
	# 注意这里使用的是executemany而不是execute，下边有对executemany的详细说明
	cs.executemany('insert into calendar_info (date,type,`desc`) values(%s,%s,%s)', usersvalues)
	conn.commit()
	cs.close()
	conn.close()
	print('数据库操作完成OK')


def workdays_info(year):
	"""描述
	工作日取数
	"""
	print("工作日取数开始")
	start = datetime.date(year, 1, 1)
	end = datetime.date(year, 12, 31)
	workdays = chinese_calendar.get_workdays(start, end)
	# for i in range(len(workdays)):
	# 	print('工作日:', workdays[i])
	print("工作日取数结束")
	return workdays


def truncatetable(year):
	conn = connect(**config)
	cs = conn.cursor()  # 获取光标
	# 注意这里使用的是executemany而不是execute，下边有对executemany的详细说明
	sql = "delete from calendar_info where date REGEXP('^" + year + ".*')"
	cs.execute(sql)
	conn.commit()
	cs.close()
	conn.close()


def deleteByYear(start, end):
	conn = connect(**config)
	cs = conn.cursor()  # 获取光标
	# 注意这里使用的是executemany而不是execute，下边有对executemany的详细说明
	sqlMatchCondition = ''
	for y in range(start, end + 1):
		sqlMatchCondition += ("^" + str(y) + ".*|")
	sqlMatchCondition = sqlMatchCondition[0:len(sqlMatchCondition) - 1]
	sql = "delete from calendar_info where date REGEXP('" + sqlMatchCondition + "')"
	print("计划清除要取的年份历史数据sql=== %s" % sql)
	delSqlResult = cs.execute(sql)
	print("删除结果:", delSqlResult)
	conn.commit()
	cs.close()
	conn.close()


if __name__ == '__main__':
	try:
		start = 2021
		end = 2022
		deleteByYear(start, end)
		# 1.获取节假日信息
		holidayDos = []
		holidaysList = []
		for year in range(start, end + 1):
			holidays = get_holidays(year)
			holidaysList.append(holidays)
		# 获取每天的详细信息 主要取节假日名称
		for i in range(len(holidaysList)):
			for j in range(len(holidaysList[i])):
				detail = chinese_calendar.get_holiday_detail(holidaysList[i][j])
				if not detail[1] is None and not detail[1][1] is None:
					# 组成对象
					hol = guowuyuanholiday.HolidayInfo(detail[1][1], holidaysList[i][j], '1')
					holidayDos.append(hol)
				else:
					hol = guowuyuanholiday.HolidayInfo('', holidaysList[i][j], '1')
					holidayDos.append(hol)
			print("%s年休息：%s 天" % (str(holidaysList[i][0])[0:4], len(holidaysList[i])))
		# 国务院假日信息爬取
		fileResult = guowuyuanholiday.queryFiles(str(start) + '-01-01', str(end) + '-01-01')
		for file in fileResult:
			holidaydos = guowuyuanholiday.downloadFile(file['url'])
			if not holidaydos is None and len(holidaydos) > 0:
				for i in range(len(holidaydos)):
					for ii in range(len(holidayDos)):
						if holidaydos[i].date == str(holidayDos[ii].date):
							holidayDos[ii].desc = holidaydos[i].desc
		# 打印
		for o in range(len(holidayDos)):
			print("---", holidayDos[o].date, holidayDos[o].type, holidayDos[o].desc)
		# 2.假日信息入库
		add_holidays_info(holidayDos)
	# workdays = workdays_info(2021)
	# print("今年工作：%s 天" % len(workdays))
	# add_holidays_info(workdays, '2')
	except BaseException as e:
		logging.exception("Error: 节假日跑批异常", e)
